// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_module/second.dart';

void main() {
  runApp(const FlutterView());
}

class FlutterView extends StatelessWidget {
  const FlutterView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'AndroidToFlutter',
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const String _channel = 'increment';
  static const BasicMessageChannel<String?> platform =
      BasicMessageChannel<String?>(_channel, StringCodec());

  EventChannel _eventChannelPlugin = EventChannel("Event_Channel");
  MethodChannel _methodChannel = MethodChannel("methodChannel");

  int _counter = 0;
  var msg = "";

  @override
  void initState() {
    super.initState();
    // platform.setMessageHandler(_handlePlatformIncrement);
    platform.setMessageHandler((message) => _handlePlatformIncrement(message!));

    _eventChannelPlugin
        //["abc", 123, "你好"]对应着Android端onListen方法的第一个参数，可不传值
        .receiveBroadcastStream(["abc", 123, "你好"]).listen(_onToDart,
            onError: _onToDartError, onDone: _onDone);

    _methodChannel.setMethodCallHandler(platformCallHandler);
  }

  Future<dynamic> platformCallHandler(MethodCall call) async {
    switch (call.method) {
      case "getPlatform":
        return "原生调用flutter 方法。返回给原生"; //调用success方法
        //          return PlatformException(code: '1002',message: "出现异常"); //调用error
        break;
    }
  }


  var response = "";
  var showMessage = "";

  //send
  void handleMethodChannelSend() async {
    try {
      response = await _methodChannel.invokeMethod("getBatteryLevel");
      print(response);
      setState(() {
        showMessage = response.toString();
      });
    } catch (e) {
      //捕获error和notImplemented异常
      setState(() {
        showMessage = e.toString();
      });
    }
  }

  //native端发送正常数据
  void _onToDart(message) {
    print(message);
    msg = message;
  }

  //当native出错时，发送的数据
  void _onToDartError(error) {
    print(error);
  }

  //当native发送数据完成时调用的方法，每一次发送完成就会调用
  void _onDone() {}

  Future<String> _handlePlatformIncrement(String message) async {
    setState(() {
      // _counter++;
      msg = message;
    });
    //原生发送到fluter成功后，给原生的反馈
    return "收到Native的消息：接受成功";
  }

  void _sendFlutterIncrement() {
    platform.send("flutter发送数据到android");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            child: Center(
              child: Column(
                children: [
                  Text(
                    'Platform button tapped $_counter time${_counter == 1 ? '' : 's'}.',
                    style: const TextStyle(fontSize: 17.0),
                  ),
                  Text('android发送过来的数据==$msg'),
                  Text('android 使用EventChannel单向发送=$msg'),
                  Text('flutter调用原生方法返回的数据=$showMessage')
                ],
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.only(bottom: 15.0, left: 5.0),
            child: Row(
              children: <Widget>[
                const Text('我是Flutter', style: TextStyle(fontSize: 30.0)),
              ],
            ),
          ),
          ElevatedButton(
              onPressed: () {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (context) => TwoPage(
                          count: _counter,
                        )));
              },
              child: Text("跳转到第二个flutter")),

          ElevatedButton(
              onPressed: handleMethodChannelSend,
              child: Text("flutter调用原生方法")),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendFlutterIncrement,
        child: const Icon(Icons.add),
      ),
    );
  }
}
